Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input
array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
反轉字串,空間複雜度為 O(1),使用reverse()
即可解決,但這會失去解題的意義。
另一個解法,找出第一個與最後一個的值互換,第二個與倒數第二個互換,以此類推...。
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
var reverseString = function (s) {
let maxLen = s.length;
let len = Math.floor(maxLen / 2);
for (let i = 0; i < len; i++) {
let tmp = s[i];
s[i] = s[maxLen - 1 - i];
s[maxLen - 1 - i] = tmp;
}
return s;
};